package ru.amse.tsyganov.jumleditor.commands;

import ru.amse.tsyganov.jumleditor.model.common.Edge;
import ru.amse.tsyganov.jumleditor.view.ConnectionPoint;
import ru.amse.tsyganov.jumleditor.view.common.EdgeView;
import ru.amse.tsyganov.jumleditor.view.lines.Line;

/*package*/ class MoveEdgeCommand extends Command {
	
	private final EdgeView<? extends Edge> movingEdge;
	
	private final ConnectionPoint oldSourceConnectionPoint;
	
	private final ConnectionPoint oldTargetConnectionPoint;
	
	private final ConnectionPoint newSourceConnectionPoint;
	
	private final ConnectionPoint newTargetConnectionPoint;
	
	private final Line[] brokenLine;

	public MoveEdgeCommand(
			EdgeView<? extends Edge> movingEdge, 
			ConnectionPoint newSourceConnectionPoint, 
			ConnectionPoint newTargetConnectionPoint) {
		
		if (movingEdge == null || newSourceConnectionPoint == null ||
				newTargetConnectionPoint == null) {
			
			throw new IllegalArgumentException();
		}
		
		this.movingEdge = movingEdge;
		oldSourceConnectionPoint = movingEdge.getSourceConnectionPoint();
		oldTargetConnectionPoint = movingEdge.getTargetConnectionPoint();
		this.newSourceConnectionPoint = newSourceConnectionPoint;
		this.newTargetConnectionPoint = newTargetConnectionPoint;
		brokenLine = movingEdge.getBrokenLine();
		
		if (oldSourceConnectionPoint == newSourceConnectionPoint &&
				oldTargetConnectionPoint == newTargetConnectionPoint) {
			
			throw new IllegalArgumentException();
		}
	}
	
	@Override
	public void execute() {
		movingEdge.getModel().setSource(newSourceConnectionPoint.
				getContainer().getModel().getStateVertex());
		
		movingEdge.getModel().setTarget(newTargetConnectionPoint.
				getContainer().getModel().getStateVertex());
		
		movingEdge.setSourceConnectionPoint(newSourceConnectionPoint);
		movingEdge.setTargetConnectionPoint(newTargetConnectionPoint);
	}

	@Override
	public void unexecute() {
		movingEdge.getModel().setSource(oldSourceConnectionPoint.
				getContainer().getModel().getStateVertex());
		
		movingEdge.getModel().setTarget(oldTargetConnectionPoint.
				getContainer().getModel().getStateVertex());
		
		movingEdge.setSourceConnectionPoint(oldSourceConnectionPoint);
		movingEdge.setTargetConnectionPoint(oldTargetConnectionPoint);
		movingEdge.initBrokenLine(brokenLine);
	}

}
